var models = require('../models/user.js');
var lession = require('../models/lession.js').lession;
var type = require('../models/lessiontype.js').lessiontype;
var moment = require('moment');
var ObjectId = require('mongoose').Types.ObjectId;
var menus = require('./menu').menu();
menus.type.active = 'active';
module.exports.autoroute = {
	get:{
		'/admin/type':function(req,res){
			res.render("type",{menu:menus})
		},
		'/admin/type/add':function(req,res){
			var id = req.query.id,_type = {name:"",_id:""};
			if(id)
				type.findById(ObjectId(id),function(err,result){
					res.render('typeadd',{menu:menus,'type':result});
				});
			else
				res.render('typeadd',{menu:menus,'type':_type});
		},
		'/admin/type/delete':function(req,res){
			var callback = function(err){
			  if(err){
			    debug(err);
			    res.send({code:-1,message:'保存失败'})
			  }else
			    res.redirect("/admin/type");
			};
			type.findByIdAndRemove(ObjectId(req.query.id),callback);
		},
		'/admin/ajax/type':function(req,res){
			var page = 0;
			if(req.query.iDisplayStart)
				page = req.query.iDisplayStart;
			condition = {};
			if(req.query.name)
				condition.name = new RegExp(req.query.name);
			type.find(condition).skip(page).limit(10).lean(true).exec(function(err,user){
				type.find().count(function(err,size){
					user.forEach(function(item){
						item.create_time = moment(item.create_time).format("YYYY-MM-DD HH:mm");
					});
		  			res.json({aaData:user,iTotalRecords:size,iTotalDisplayRecords:size});
				})
			});
		}
	},
	post:{
		'/admin/type/save':function(req,res){
			var callback = function(err){
			  if(err){
			    debug(err);
			    res.send({code:-1,message:'保存失败'})
			  }else
			    res.redirect("/admin/type");
			};

			if(req.body.id){
				type.findByIdAndUpdate(ObjectId(req.body.id),{'name' : req.body.name},callback);
			}
			else{
				var _type = new type({
				  'name' : req.body.name, 
				});
				_type.save(callback);
			}
		}
	}
};

